//
//  StudyManager.m
//  LineByLine
//
//  Created by 병철 김 on 11. 10. 25..
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "StudyManager.h"
#import "CoreDataManager.h"


@implementation StudyManager

+ (StudyManager*) sharedStudyManager {
    static dispatch_once_t onceToken;
    static StudyManager *sharedInstance = nil;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

- (void)dealloc {
    [startTime release];
    [super dealloc];
}

- (void) setBook:(id) book step:(NSNumber*) step currentPage:(NSNumber*) page {
    id studyInfo = [[CoreDataManager sharedCoreDataManager] selectOneFrom:@"StudyInfo" where:@"book=%@ and step=%@", book, step, nil];
    if (studyInfo == nil) {
        studyInfo = [[CoreDataManager sharedCoreDataManager] insertOneInto:@"StudyInfo" values:@"book", book, @"step", step, nil];
    }
    
    [[CoreDataManager sharedCoreDataManager] update:studyInfo values:@"page", page, nil];
}

- (NSNumber*) pageOfBook:(id) book step:(NSNumber*) step {
    id studyInfo = [[CoreDataManager sharedCoreDataManager] selectOneFrom:@"StudyInfo" where:@"book=%@ and step=%@", book, step, nil];
    if (studyInfo != nil) {
        return [studyInfo valueForKey:@"page"];
    } else {
        return [NSNumber numberWithInt:1];
    }
}

- (void) startTimerWith:(void*) object {
    timerObject = object;
    [startTime release];
    startTime = nil;
    startTime = [[NSDate alloc] init];
}

- (NSTimeInterval) stopTimerWith:(void*) object {
    if (timerObject == object) {
        NSDate *current = [NSDate date];
        NSTimeInterval time = [current timeIntervalSinceDate:startTime];
        [startTime release];
        startTime = nil;
        return time;
    } else {
        return 0;
    }
}

@end
